<?php defined('BASEPATH') || exit('No direct script access allowed');

/**
 * Building photo controller
 */
class Bhuxing extends Admin_Controller
{
    protected $permissionCreate = 'Buildings.Content.Create';
    protected $permissionDelete = 'Buildings.Content.Delete';
    protected $permissionEdit   = 'Buildings.Content.Edit';
    protected $permissionView   = 'Buildings.Content.View';

    protected $photoSubType = 4;
    /**
     * Constructor
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        
        $this->auth->restrict($this->permissionView);
        $this->load->model('buildings/buildings_model');
        $this->load->model('buildings/buildingshuxing_model');
        $this->load->model('buildings/photos_model');
        $this->load->model('area/area_model');
        $this->load->model('vendor/vendor_model');
        $this->load->model('category/category_model');
        $this->lang->load('buildings');
        
        $this->form_validation->set_error_delimiters("<span class='error'>", "</span>");
        
        Template::set_block('sub_nav', 'building/_sub_nav');

        Assets::add_module_js('buildings', 'huxing.js');
        Assets::add_css(array('plugins/select2/select2.min.css', 'plugins/iCheck/all.css', 'plugins/datepicker/datepicker3.css'));
        Assets::add_js(array(Template::theme_url('plugins/select2/select2.full.min.js'), 
                            Template::theme_url('plugins/iCheck/icheck.min.js'), 
                            Template::theme_url('plugins/datepicker/bootstrap-datepicker.js'), 
                            Template::theme_url('js/plupload-2.1.1/plupload.full.min.js'),
                            Template::theme_url('js/plupload-2.1.1/i18n/zh_CN.js'), 
                            Template::theme_url('js/qiniu.js')
                            ));
    }

    /**
     * Display a list of Buildings data.
     *
     * @return void
     */
    public function index($buildingId, $offset = 0)
    {
        // Deleting anything?
        if (isset($_POST['delete'])) {
            $this->auth->restrict($this->permissionDelete);
            $checked = $this->input->post('checked');
            if (is_array($checked) && count($checked)) {

                // If any of the deletions fail, set the result to false, so
                // failure message is set if any of the attempts fail, not just
                // the last attempt

                $result = true;
                foreach ($checked as $pid) {
                    $deleted = $this->buildingshuxing_model->delete($pid);
                    if ($deleted == false) {
                        $result = false;
                    }
                }
                if ($result) {
                    Template::set_message(count($checked) . ' ' . lang('buildings_delete_success'), 'success');
                } else {
                    Template::set_message(lang('buildings_delete_failure') . $this->buildingshuxing_model->error, 'error');
                }
            }
        }

        $where = array('deleted'=>0, 'building_id'=>$buildingId);
        $totalRows = $this->buildingshuxing_model->where($where)->count_all();
        $this->buildingshuxing_model->where($where);

        $pagerUriSegment = 5;
        $pagerBaseUrl = site_url('/buildings/bhuxing/index').'/'.$buildingId. '/';
        
        $limit  = $this->settings_lib->item('site.list_limit') ?: 15;

        $this->load->library('pagination');
        $this->pager['base_url']    = $pagerBaseUrl;
        $this->pager['total_rows']  = $totalRows;
        $this->pager['per_page']    = $limit;
        $this->pager['uri_segment'] = $pagerUriSegment;

        $this->pagination->initialize($this->pager);
        $this->buildingshuxing_model->limit($limit, $offset);
        
        $records = !empty($records) ? $records : $this->buildingshuxing_model->find_all();

        Template::set('records', $records);

        Template::set('index_url', $pagerBaseUrl);
        Template::set('toolbar_title', lang('buildings_manage'));

        // Template::render();
        $data['index_url'] = $pagerBaseUrl;
        $data['records'] = $records;
        $data['buildingId'] = $buildingId;
        $this->load->view('bphoto/header');
        $this->load->view('bhuxing/index', $data);
        $this->load->view('bphoto/footer');
    }
    
    /**
     * Create a Buildings object.
     *
     * @return void
     */
    public function create($buildingId)
    {
        $this->auth->restrict($this->permissionCreate);
        
        if (isset($_POST['save'])) {
            if ($insert_id = $this->save_buildings()) {
                log_activity($this->auth->user_id(), lang('buildings_act_create_record') . ': ' . $insert_id . ' : ' . $this->input->ip_address(), 'buildings');
                Template::set_message(lang('buildings_create_success'), 'success');

                $pagerBaseUrl = site_url('/buildings/bhuxing/index').'/'.$buildingId.'/';
                redirect($pagerBaseUrl);
            }

            // Not validation error
            if ( ! empty($this->photos_model->error)) {
                Template::set_message(lang('buildings_create_failure') . $this->photos_model->error, 'error');
            }
        }

        // Template::render();
        $data['buildingId'] = $buildingId;
        $data['rooms'] = building_room_number();
        $data['roomsType'] = building_room_type();
        $this->load->view('bphoto/header');
        $this->load->view('bhuxing/create', $data);
        $this->load->view('bphoto/footer');
    }
    /**
     * Allows editing of Buildings data.
     *
     * @return void
     */
    public function edit($buildingId)
    {
        $id = $this->uri->segment(5);
        if (empty($id)) {
            Template::set_message(lang('buildings_invalid_id'), 'error');

            redirect(SITE_AREA . '/building/buildings');
        }
        
        if (isset($_POST['save'])) {
            $this->auth->restrict($this->permissionEdit);

            if ($this->save_buildings('update', $id)) {
                log_activity($this->auth->user_id(), lang('buildings_act_edit_record') . ': ' . $id . ' : ' . $this->input->ip_address(), 'buildings');
                Template::set_message(lang('buildings_edit_success'), 'success');
                $pagerBaseUrl = site_url('/buildings/bhuxing/index').'/'.$buildingId.'/';
                redirect($pagerBaseUrl);
            }

            // Not validation error
            if ( ! empty($this->buildingshuxing_model->error)) {
                Template::set_message(lang('buildings_edit_failure') . $this->buildingshuxing_model->error, 'error');
            }
        }
        
        elseif (isset($_POST['delete'])) {
            $this->auth->restrict($this->permissionDelete);

            if ($this->buildingshuxing_model->delete($id)) {
                log_activity($this->auth->user_id(), lang('buildings_act_delete_record') . ': ' . $id . ' : ' . $this->input->ip_address(), 'buildings');
                Template::set_message(lang('buildings_delete_success'), 'success');

                redirect(SITE_AREA . '/building/buildings');
            }

            Template::set_message(lang('buildings_delete_failure') . $this->buildingshuxing_model->error, 'error');
        }
        
        $huxing = $this->buildingshuxing_model->find($id);
        $huxingPhotos = $this->photos_model->photosBy($buildingId, $id, 1, $this->photoSubType);

        if($huxingPhotos){
            foreach($huxingPhotos as $key=>$value){
                    switch ($value->platform) {
                        case '1':
                            $huxing->photos_pc[$key] = $huxingPhotos[$key] ? : [];
                            break;             
                        case '2':
                            $huxing->photos_mobile[$key] = $huxingPhotos[$key]? : [];
                            break;
                    }
            }

        }
        //$huxing->photos = $huxingPhotos ? : [];
        //dump($huxing);exit();
        $data['buildingId'] = $buildingId;
        $data['huxing'] = $huxing;
        $data['rooms'] = building_room_number();
        $data['roomsType'] = building_room_type();
        $this->load->view('bphoto/header');
        $this->load->view('bhuxing/edit', $data);
        $this->load->view('bphoto/footer');
    }

    //--------------------------------------------------------------------------
    // !PRIVATE METHODS
    //--------------------------------------------------------------------------

    /**
     * Save the data.
     *
     * @param string $type Either 'insert' or 'update'.
     * @param int    $id   The ID of the record to update, ignored on inserts.
     *
     * @return boolean|integer An ID for successful inserts, true for successful
     * updates, else false.
     */
    private function save_buildings($type = 'insert', $id = 0)
    {
        if ($type == 'update') {
            $_POST['id'] = $id;
        }

        // Validate the data
        // $this->form_validation->set_rules($this->buildings_model->get_validation_rules());
        // if ($this->form_validation->run() === false) {
        //     return false;
        // }

        // Make sure we only pass in the fields we want
        $post = $this->input->post();
        $data = $this->buildingshuxing_model->prep_data($post);
        $buildingId = $post['building_id'];
        $urlArr = isset($post['url']) ? $post['url'] : null;
        $platformArr =  isset($post['platform']) ? $post['platform'] : null;
// print_r($post);
// print_r($urlArr);
// exit;
        // Additional handling for default values should be added below,
        // or in the model's prep_data() method

        $return = false;
        if ($type == 'insert') {
            $id = $this->buildingshuxing_model->insert($data);
            // 户型图
            if (is_array($urlArr)) $this->photos_model->addHuxingPhotos($buildingId, $id, $urlArr,$platformArr);
            if (is_numeric($id)) {
                $return = $id;
            }
        } elseif ($type == 'update') {
            $return = $this->buildingshuxing_model->update($id, $data);
            // 户型图
            if (is_array($urlArr)) $this->photos_model->addHuxingPhotos($buildingId, $id, $urlArr,$platformArr);
        }

        return $return;
    }

    /**
     * 删除数据
     */
    public function delete($buildingId)
    {
        $bid = $this->uri->segment(4);
        $id = $this->uri->segment(5);
        if (empty($id)) {
            Template::set_message(lang('channel_invalid_id'), 'error');

            redirect(SITE_AREA . '/building/buildings');
        }

        $this->auth->restrict($this->permissionDelete);

        if ($this->buildingshuxing_model->delete($id)) {
            $where = "target_id = {$bid} and target_sub_id = {$id}";
            $this->photos_model->delete_where($where);
            log_activity($this->auth->user_id(), lang('channel_act_delete_record') . ': ' . $id . ' : ' . $this->input->ip_address(), 'channel');
            Template::set_message(lang('channel_delete_success'), 'success');

            $pagerBaseUrl = site_url('/buildings/bhuxing/index').'/'.$buildingId.'/';
            redirect($pagerBaseUrl);
        }

    }
}